<template>
	<view class="main animated fadeIn faster" style="min-height: 100vh; background: #fff;">
		<TitleBarVue :title="title" />
		<view class="bg-fff rounded30 px-2 pt-3" style="padding-top: 190rpx;">
			<view class="d-flex d-flex-between" style="margin-left: 20rpx; margin-bottom: 20rpx;margin-top: 20rpx;">
				<view v-if="!flag" class="font30 font-bold">
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/position.png"
						style="    width: 37rpx;height: 42rpx;"></image>定位失败，请先<span class="colorblue"
						@click="jumpToPermissionSettings">开启定位服务</span>
				</view>
				<view v-else class="font30 font-bold">
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/position.png"
						style="    width: 37rpx;height: 42rpx;"></image>定位成功，当前的城市为：{{city}}
				</view>
				<view class="font30 font-bold colorblue" @click="getLocation">
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/position2.png"
						style=" width: 37rpx;height: 42rpx;"></image>重新定位
				</view>
			</view>
			<view></view>
			<picker @columnchange="ColumnChange" mode="multiSelector" :range="areaData" :value="currentIndex"
				@change="onPickerChange">
				<view class="picker-view">
					当前选择：{{ selectedProvince }} - {{ selectedCity }}
				</view>
			</picker>
		</view>
	</view>
</template>

<script>
	import store from '@/store/index.js';
	import { mapActions } from 'vuex'
	import TitleBarVue from '../../components/TitleBar.vue';
	import provinceAndCityData from 'china-area-data';
	import { userApi } from '../../http/userApi';
	export default {
		data() {
			return {
				title: '选择城市',
				// areaData: [], // 用来存放省份和城市数据的二维数组
				currentIndex: [0, 0], // 初始选中的索引，默认第一个省份和第一个城市
				selectedProvince: '', // 当前选中的省份
				selectedCity: '', // 当前选中的城市
				city: null,
				province: '',
				index: 0,
				provinceList: [], // 所有省份
				cityList: [], // 所有省份对应的城市二维数组
				latitude: '', //纬度
				longitude: '', //经度
				address: this.addr,
				flag: null, //是否成功获取地址
				param: {},
				storedProvince: '',
				storedCity: ''
			}
		},
		components: {
			TitleBarVue
		},
		onLoad() {
			this.initAreaData();
			this.requestLocationPermission();
			this.getLocation();
			const stored = uni.getStorageSync('selectedCity');
			if (stored) {
				this.selectedProvince = stored.province;
				this.selectedCity = stored.city;
			}
		},
		methods: {
			...mapActions('permissionToast', ['requstPermission']),
			async putPosition() {
				this.param.uid = store.state.user.uid
				console.log(this.param);
				let res = await userApi.putPosition(this.param);
				console.log(res);
			},
			initAreaData() {
				// 确保 provinceAndCityData 结构符合预期且有数据
				if (!provinceAndCityData || typeof provinceAndCityData !== 'object') {
					console.error('provinceAndCityData 数据结构不符合预期，请检查模块数据');
					return;
				}
				const provinces = [];
				const cities = [];
				// 获取省份信息（假设数据结构里以86作为顶层键，其值为包含省份信息的对象）
				const provinceObj = provinceAndCityData[86];
				if (!provinceObj || typeof provinceObj !== 'object') {
					console.error('省份数据结构不符合预期，请检查数据内容');
					return;
				}
				// 遍历省份对象，提取省份名称并处理成字符串形式（例如将["北", "京", "市"]处理成"北京市"）
				for (const provinceCode in provinceObj) {
					let i = 0;
					if (provinceObj.hasOwnProperty(provinceCode)) {
						const provinceNameArr = provinceObj[provinceCode];
						let provinceName;
						// 判断是数组还是字符串类型，分别进行处理
						if (Array.isArray(provinceNameArr)) {
							provinceName = provinceNameArr.join('');
						} else if (typeof provinceNameArr === 'string') {
							provinceName = provinceNameArr;
						} else {
							console.error(`省份代码 ${provinceCode} 对应的省份名称数据格式不正确，期望是数组或字符串类型，实际为 ${typeof provinceNameArr}`);
							continue;
						}
						provinces.push(provinceName); //省名字
						const cityList = this.getCityList(provinceCode, provinceObj[provinceCode]);
						cities.push(cityList); //城市名字
						// console.log(provinceName,cityList);
					}
				}
				// 读取缓存
				const storedCity = uni.getStorageSync('selectedCity') || {
					province: '北京市',
					city: '北京市'
				};
				// 查找省份索引
				let provinceIndex = provinces.findIndex(p => p === storedCity.province);
				let cityIndex = 0;
				if (provinceIndex > -1) {
					const targetCities = cities[provinceIndex];
					cityIndex = targetCities.findIndex(c => c === storedCity.city);
					provinceIndex = provinceIndex === -1 ? 0 : provinceIndex;
					cityIndex = cityIndex === -1 ? 0 : cityIndex;
				} else {
					provinceIndex = 0;
					cityIndex = 0;
				}
				this.provinceList = provinces;
				this.cityList = cities;
				// 初始化时设置默认选中项
				this.currentIndex = [provinceIndex, cityIndex];
				this.selectedProvince = provinces[provinceIndex];
				this.selectedCity = cities[provinceIndex][cityIndex];
				// 关键修复：根据缓存省份初始化城市数据
				this.areaData = [provinces, cities[provinceIndex]]; // 而不仅仅是cities[0]
			},
			ColumnChange(e) {
				if (e.detail.column === 0) {
					const provinceIndex = e.detail.value;
					// 强制更新城市数据
					this.currentIndex = [provinceIndex, 0];
					this.$forceUpdate(); // 重要：强制视图更新

					// 自动选择第一个城市
					this.$nextTick(() => {
						this.selectedProvince = this.provinceList[provinceIndex];
						this.selectedCity = this.cityList[provinceIndex][0];
					});
				}
			},
			getCityList(provinceCode, provinceName) {
				let cityList = [];
				// 检查省份下是否有城市
				if (provinceAndCityData[provinceCode]) {
					for (const cityCode in provinceAndCityData[provinceCode]) {
						const cityName = provinceAndCityData[provinceCode][cityCode];
						// 直辖市特殊处理，直接返回区级数据
						if (cityName === '市辖区') {
							const districts = this.getDistricts(cityCode);
							cityList = cityList.concat(districts);
						} else {
							cityList.push(cityName);
						}
					}
				}
				return cityList;
			},
			getDistricts(cityCode) {
				let districts = [];
				if (provinceAndCityData[cityCode]) {
					for (const districtCode in provinceAndCityData[cityCode]) {
						const districtName = provinceAndCityData[cityCode][districtCode];
						districts.push(districtName);
					}
				}
				return districts;
			},
			onPickerChange(e) {
				const [provinceIndex, cityIndex] = e.detail.value;
				// 确保索引有效性
				const safeCityIndex = Math.min(cityIndex, this.cityList[provinceIndex].length - 1);

				this.selectedProvince = this.provinceList[provinceIndex];
				this.selectedCity = this.cityList[provinceIndex][safeCityIndex];

				// 处理特殊行政区
				if (this.selectedProvince.startsWith("香港") ||
					this.selectedProvince.startsWith("澳门")) {
					this.selectedCity = this.selectedProvince.replace("特别行政区", "");
				}
				// 处理直辖市逻辑（保持原逻辑）
				if (this.selectedProvince.endsWith("市")) {
					this.selectedCity = this.selectedProvince
				}

				this.param.locatedCity = this.selectedCity;
				this.param.latitude = null
				this.param.longitude = null
				this.putPosition()
				store.commit("setPosition", this.selectedCity);

				uni.showToast({
					title: '更新位置成功',
					icon: 'none', // 使用'none'图标，只显示文字
					duration: 1000 // 显示持续时间
				});

				setTimeout(function() {
					uni.navigateBack();
				}, 1000);

				uni.setStorageSync('selectedCity', {
					province: this.selectedProvince,
					city: this.selectedCity
				});
			},
			ArrayChangeByObject(obj) {
				if (Object.prototype.toString.call(obj) !== "[object Object]") return [];
				let arr = [];
				for (const key in obj) {
					if (obj.hasOwnProperty(key)) {
						arr.push(obj[key]);
					}
				}
				return arr;
			},
			FindCodeByValue(obj, str) {
				for (const key in obj) {
					if (obj.hasOwnProperty(key)) {
						if (obj[key] === str) return key;
					}
				}
			},
			requestLocationPermission() {
				//#ifdef MP-WEIXIN
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						this.getLocation();
					},
					fail: () => {
						uni.showModal({
							title: '提示',
							content: '需要您授权地理位置权限',
							success: (res) => {
								if (res.confirm) {
									// 用户点击确定后重新请求权限
									this.getLocation();
								} else {
									console.log("点击取消");
									// 用户点击取消后的逻辑
								}
							}
						});
					}
				});
				//#endif
			},
			jumpToPermissionSettings() {
				uni.openAppAuthorizeSetting({
					success: function() {
						console.log('成功打开应用权限设置页面');
					},
					fail: function(err) {
						console.error('打开应用权限设置页面失败', err);
					}
				});
			},
			async getLocation() {
				uni.getLocation({
					geocode: true,
					success: (res) => {
						this.flag = true;
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						let params = {
							latitude: this.latitude,
							longitude: this.longitude
						}
						this.param.latitude = this.latitude;
						this.param.longitude = this.longitude;
						this.putPosition().then(() => {
							this.getPositionInfo()
						})
						store.commit("setItude", params);
						uni.showToast({
							title: '获取位置成功',
							icon: 'none', // 使用'none'图标，只显示文字
							duration: 1000 // 显示持续时间
						});
					},
					fail: () => {
						this.flag = false;
						uni.showModal({
							title: '获取位置失败',
							content: '请确保已开启定位权限',
							showCancel: false
						});
					}
				});
			},
			async getPositionInfo() {
				try {
					let params = {
						dressedVoMap: 1
					}
					const res = await userApi.getUserInfo(params)
					this.city = res.locatedCity
				} catch (e) {
					console.log('login-info', e)
				}
			}
		},
		computed: {
			areaData() {
				return [this.provinceList, this.cityList[this.currentIndex[0]] || []];
			}
		},
	}
</script>

<style>
	.picker-view {
		border: 1px solid #ccc;
		padding: 10px;
		border-radius: 5px;
	}

	.citybox {
		border: 1rpx solid #e2e2e2;
		width: 174rpx;
		height: 67rpx;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.topline {
		border-top: 1px solid #e2e2e2;
		border-left: none;
		border-right: none;
		border-bottom: none;
	}
</style>